package com.china08.yxyapi.api.home.weikecheng;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserMark;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.mg.YxyUserMarkRepository;
import com.china08.yxyapi.util.EsResourceUpdateUtil;

/**
 * 评价微课---适用于各种角色
 * 
 */
@CrossOrigin
@RestController
public class WeikeMarkController extends YxyApiBaseController {

    @Autowired
    private YxyUserMarkRepository markRepository;

    @Autowired
    private YxyResResourceRepository resourceRepository;

    @Autowired
    private MongoTemplate mt;

    @ResponseBody
    @RequestMapping(value = "/api_yw/home/weike/mark/crt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel,
            RespModel respModel) {

        reqModel.check();
        respModel = new RespModel();
        String userId = getProfile(request, response).getId();
        YxyResResource resource = resourceRepository.findById(reqModel.weikeId);
        Assert.notNull(resource, "发生错误,请刷新页面");
        YxyUserMark mark = markRepository.findByResIdAndUserId(reqModel.weikeId, userId);
        if (mark == null) {
            mark = new YxyUserMark();
        }
        mark.setMark(reqModel.mark);
        mark.setUserId(userId);
        mark.setResId(reqModel.weikeId);
        markRepository.save(mark);

        Criteria criteria = Criteria.where("resId").is(reqModel.weikeId);
        // 更新评分字段
        TypedAggregation<YxyUserMark> aggregation1 = Aggregation.newAggregation(YxyUserMark.class, match(criteria),
                group("resId").count().as("count").sum("mark").as("markTotal"),
                Aggregation.project("markTotal", "count").and("resId"));
        AggregationResults<YxyUserMark> result = mt.aggregate(aggregation1, YxyUserMark.class);

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> resultsList = (List<Map<String, Object>>) result.getRawResults().get("result");
        if (resultsList != null && resultsList.size() > 0) {
            Integer markTotal = (Integer) resultsList.get(0).get("markTotal");
            Integer count = (Integer) resultsList.get(0).get("count");
            float markEva = (float) ((markTotal * 1.0) / count);
            resource.setMark(markEva);
            resourceRepository.save(resource);
        }

        // 重建索引
        EsResourceUpdateUtil.updateEsResoure(reqModel.weikeId);
        respModel.setMessage("评价成功");
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public int mark;// 1-5 分

        public String weikeId;

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(weikeId, null), "微课id不能为空");
            Assert.notNull(mark, "评分分值不能为空");
        }
    }

    protected static class RespModel extends YxyApiRespModel {
    }

}
